package com.yf.mediaserver.controller;


import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.yf.mediaserver.gb.cmd.SIPRequestHeaderProvider;
import com.yf.mediaserver.gb.config.SipConfig;
import com.yf.mediaserver.gb.sip.processors.SIPSender;
import com.yf.mediaserver.zlm.ZLMUtil;
import com.yf.mediaserver.zlm.bean.ZlMHookResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * 定位一个流媒体源个元素
 * 协议(scheam)
 * 虚拟主机(vhost) -> IP时值为：__defaultVhost__
 * 应用名(app)
 * 流ID(streamid)
 */
@Slf4j
@RestController
@RequestMapping("/sip")
public class SipController {

    @Resource
    private SIPSender sipSender;
    @Resource
    private SipConfig sipConfig;

    @Resource
    private SIPRequestHeaderProvider sipRequestHeaderProvider;
   private static final String STREAM_ID = "34020000001320000001_34020000001320000001";


    /**
     * @param app 协议
     * @param vhost 虚拟主机
     * @param stream 应用名
     * @param schema 流ID
     * @return
     */
    @GetMapping("/media_list")
    public String getMediaList(
            @RequestParam(required = false)String app,
            @RequestParam(required = false)String vhost,
            @RequestParam(required = false)String stream,
            @RequestParam(required = false)String schema
    )  {
        ZlMHookResult<?> mediaList = ZLMUtil.getMediaList(app,vhost,stream,schema);
        return JSONUtil.toJsonStr(mediaList);
    }



    @GetMapping("/invite/{channelId}")
    public String invite(@PathVariable("channelId")String channelId)  {
        String streamId = String.format("%s_%s",channelId,channelId);
        ZlMHookResult<?> zlMResp = ZLMUtil.openRtpServer(streamId);
        if(zlMResp.fail()){
            log.info("开始RtpServer失败");
            return zlMResp.getMsg();
        }

        Integer port = zlMResp.getPort();
        String deviceAddr = "192.168.1.65:5061";
        String ssrcPrefix = sipConfig.getDomain().substring(3, 8);
        //数据头 视频0  录像1
        String ssrc = String.format("0%s%04d", ssrcPrefix, RandomUtil.randomInt(1000) + 1);
//        String ssrc = String.format("1%s%04d", ssrcPrefix, RandomUtil.randomInt(1000) + 1);

        String content = getContent(channelId, ZLMUtil.ZLM_IP,"UDP",ssrc,port);
        sipRequestHeaderProvider.sendInviteRequest(channelId, sipConfig.getAddr(), deviceAddr, content, ssrc);
        return "Send Invite Request Success";
    }


    public String getContent(String channelId, String sdpIp, String mode,String ssrc, Integer port) {
        String next = "\r\n";
        StringBuilder content = new StringBuilder(200);
        content.append("v=0").append(next);
        content.append("o=").append(channelId).append(" 0 0 IN IP4 ").append(sdpIp).append(next);
        content.append("s=Play").append(next);
        content.append("c=IN IP4 ").append(sdpIp).append(next);
        content.append("t=0 0").append(next);

        if ("TCP-PASSIVE".equalsIgnoreCase(mode)) {
            content.append("m=video ").append(port).append(" TCP/RTP/AVP 96 97 98 99").append(next);
        } else if ("TCP-ACTIVE".equalsIgnoreCase(mode)) {
            content.append("m=video ").append(port).append(" TCP/RTP/AVP 96 97 98 99").append(next);
        } else if ("UDP".equalsIgnoreCase(mode)) {
            content.append("m=video ").append(port).append(" RTP/AVP 96 97 98 99").append(next);
        }
        content.append("a=recvonly").append(next);
        content.append("a=rtpmap:96 PS/90000").append(next);
        content.append("a=rtpmap:98 H264/90000").append(next);
        content.append("a=rtpmap:97 MPEG4/90000").append(next);
        content.append("a=rtpmap:99 H265/90000").append(next);
        if ("TCP-PASSIVE".equalsIgnoreCase(mode)) {
            // tcp被动模式
            content.append("a=setup:passive").append(next);
            content.append("a=connection:new").append(next);
        } else if ("TCP-ACTIVE".equalsIgnoreCase(mode)){
            // tcp主动模式
            content.append("a=setup:active").append(next);
            content.append("a=connection:new").append(next);
        }

        content.append("y=").append(ssrc).append(next);
        return content.toString();
    }


}
